package com.study.sysuserinfo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.exception.DigitalException;
import com.study.mapper.SysUserInfoMapper;
import com.study.model.dto.SysUserDTO;
import com.study.model.user.SysUserInfo;
import com.study.sysuserinfo.service.SysUserService;
import com.study.utils.Result;
import com.study.utils.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserInfoMapper, SysUserInfo> implements SysUserService {

    @Autowired
    private SysUserInfoMapper sysUserInfoMapper;
    @Override
    public String encryptPassword(String password) {
        return DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
    }

    @Override
    public Result<String> SysUserAdd(SysUserDTO userDTO) {
        SysUserInfo adduser = new SysUserInfo();
        // 1、检查用户名是否已经存在
        LambdaQueryWrapper<SysUserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserInfo::getUsername, userDTO.getUsername());
        SysUserInfo existSysUserInfo = sysUserInfoMapper.selectOne(queryWrapper);
        if(existSysUserInfo != null) {
            return Result.error(ResultCodeEnum.ADMIN_ACCOUNT_EXIST_ERROR.getMessage());
        }
        adduser.setUsername(userDTO.getUsername());
        adduser.setPassword(encryptPassword(userDTO.getPassword()));
        adduser.setName(userDTO.getName());
        adduser.setPhone(userDTO.getPhone());
        adduser.setEmail(userDTO.getEmail());
        boolean result = sysUserInfoMapper.insert(adduser) > 0;
        return result ? Result.success("新增用户成功") : Result.error(ResultCodeEnum.FAIL.getMessage());
    }

    @Override
    public Result<String> SysUserDeleteByUsername(String username) {
        // 1、检查用户名是否已经存在
        LambdaQueryWrapper<SysUserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserInfo::getUsername,username);
        SysUserInfo existSysUserInfo = sysUserInfoMapper.selectOne(queryWrapper);
        if(existSysUserInfo == null) {
            return Result.error("需要删除的用户不存在");
        }
        int result = sysUserInfoMapper.deleteById(existSysUserInfo.getId());
        if(result > 0) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }
}
